package com.xiaohu.demo.service.common.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.engine.internal.Collections;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.xiaohu.demo.dao.common.CommonDao;
import com.xiaohu.demo.service.common.CommonService;
import com.xiaohu.demo.utils.pageModel.PageModel;

@Service("commonService")
public class CommonServiceImpl implements CommonService{
	
	@Resource
	private CommonDao commonDao;

	@Override
	public void buildDateList(PageModel pageModel) {
		//分页
		String sql = pageModel.getSql();
		List<Map<String,Object>> list = commonDao.queryForList(sql);
		if(!CollectionUtils.isEmpty(list)) {
			int pageNo = pageModel.getPageNo();
			int pageSize = pageModel.getPageSize();
			int totalRecord = list.size();
			pageModel.setTotalRecord(totalRecord);
			int totalPage = totalRecord % pageSize == 0 ?totalRecord / pageSize:totalRecord / pageSize+1;
			pageModel.setTotalPage(totalPage);
			int start = 1;
			int end = 5;
			if (totalPage <= 5) {
				// 总页数都小于5，那么end就为总页数的值了。
				end = totalPage;
			} else {
				// 总页数大于5，那么就要根据当前是第几页，来判断start和end为多少了，
				start = pageNo - 2;
				end = pageNo + 2;

				if (start < 0) {
					// 比如当前页是第1页，或者第2页，那么就不如和这个规则，
					start = 1;
					end = 5;
				}
				
				if(end > totalPage){
	                  //比如当前页是倒数第2页或者最后一页，也同样不符合上面这个规则
	                 end = totalPage;
	                 start = end - 5;
	            }
	        }
			
			pageModel.setStart(start);
			pageModel.setEnd(end);
			
			//计算从第几条开始
			int startIndex = (pageNo-1) * pageSize;
			pageModel.setStartIndex(startIndex);
			int endIndex = startIndex + pageSize;
			if(endIndex >= totalRecord) {
				endIndex = totalRecord;
			}
			List l = new ArrayList();
			for(int i = startIndex ; i < endIndex ; i++) {
				l.add(list.get(i));
			}
			pageModel.setPageData(l);
		}
		
	}
	
}
